<?php

use think\Db;

function C($name)
{
	$config = cache('systemConfig');
	if ($config) {
		$value = '';
		foreach ($config as &$v) {
			if ($v['name'] == $name) {
				$value = $v['output_value'];
				break;
			}
		}

		return $value;
	} else {
		return '';
	}
}

/**
 * 系统加密方法
 * @param        string        $data          要加密的字符串
 * @param        int           $expire        过期时间 (单位:秒)
 * @return string
 */
function thinkEncrypt($data, $expire = 0)
{
	$key = md5('083d9a270e6e16b2fbb08d35067aae5f');
	$data = base64_encode($data);
	$x = 0;
	$len = strlen($data);
	$l = strlen($key);
	$char = '';
	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}
	$str = sprintf('%010d', $expire ? $expire + time() : 0);
	for ($i = 0; $i < $len; $i++) {
		$str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
	}

	return str_replace('=', '', base64_encode($str));
}

/**
 * 系统解密方法
 * @param        string        $data        要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @return string
 */
function thinkDecrypt($data)
{
	$key = md5('083d9a270e6e16b2fbb08d35067aae5f');
	$x = 0;
	$data = base64_decode($data);
	$expire = substr($data, 0, 10);
	$data = substr($data, 10);
	if ($expire > 0 && $expire < time()) {
		return '';
	}
	$len = strlen($data);
	$l = strlen($key);
	$char = $str = '';
	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}
	for ($i = 0; $i < $len; $i++) {
		if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
			$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
		} else {
			$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
		}
	}

	return base64_decode($str);
}

/**
 * 检查验证码
 * */
function checkVerify($code)
{
	$verify = new \think\captcha\Captcha();

	return $verify->check($code);
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl()
{
	if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
		return true;
	} else if (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
		return true;
	}

	return false;
}

/**
 * 获取域名前缀
 * */
function getHost()
{
	$res = is_ssl();
	if ($res) {
		return 'https://' . $_SERVER['HTTP_HOST'];
	} else {
		return 'http://' . $_SERVER['HTTP_HOST'];
	}
}

/**
 * 按综合方式输出通信数据
 * @param        integer        $result        状态码
 * @param        string         $msg           提示信息
 * @param        array          $data          数据
 * @return string
 */
function apiReturn($result, $msg = '', $data = false)
{
	if (!is_numeric($result)) {
		return '';
	}

	return apiJson($result, $msg, $data);
}

/**
 * 按json方式输出通信数据
 * @param        integer        $result        状态码
 * @param        string         $msg           提示信息
 * @param        array          $data          数据
 * @return string
 */
function apiJson($result, $msg = '', $data = false)
{

	if (!is_numeric($result)) {
		return '';
	}

	if ($data > 0 || $data === []) {
		$message = array(
			'result' => $result,
			'msg' => $msg,
			'data' => $data ? $data : []
		);
	} else {
		$message = array(
			'result' => $result,
			'msg' => $msg,
			'data' => $data ? $data : ''
		);
	}

	echo json_encode($message);
	exit;
}

/**
 * 一维数组去重
 * */
function a_array_unique($array)
{
	$out = array();
	foreach ($array as $key => $value) {
		if (!in_array($value, $out)) {
			$out[$key] = $value;
		}
	}

	return $out;
}

function getTypeList()
{
	$type_list = cache('type_list');

	if (!$type_list) {
		$type_list = Db::name('type')->where(['pid' => 0, 'is_nav' => 1])->order('sort asc')->limit(9)->select();
		if ($type_list) {
			$i = 0;
			$menu_arr = [];
			foreach ($type_list as &$v) {
				$two_type_list = Db::name('type')->where(['pid' => $v['id']])->order('sort asc')->select();
				if ($two_type_list) {
					$v['two_type_list'] = $two_type_list;
					$v['menu_id'] = $i;
					$menu_arr[] = 'menu' . $i;
					++$i;
				} else {
					$v['two_type_list'] = [];
					$v['menu_id'] = '';
				}
			}
		}
		cache('menu_arr', json_encode($menu_arr));
	}

	return $type_list;
}

/**
 * 获取分类名
 * @param        int        $id        分类id
 * @return      string
 * */
function getTypeName($id)
{
	$name = Db::name('type')->where(['id' => $id])->column('name');

	return $name[0] ?? '';
}

/**
 * 获取文件扩展名
 * @param $filename  varchar  文件路径
 * @return mixed
 */
function getExtension($filename)
{
	$myext = substr($filename, strrpos($filename, '.'));

	return str_replace('.', '', $myext);
}

/**
 * 时间戳格式化
 * @param        int        $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = null, $format = 'Y-m-d H:i')
{
	$time = $time === null ? NOW_TIME : intval($time);

	return date($format, $time);
}

/**
 * 根据图片id获取图片路径
 * */
function getPicture($id)
{
	$path = Db::name('picture')->where(['id' => $id])->column('path');
	if($path[0]){
		return getHost() . $path[0];
	}else{
		return '';
	}
}


/**
 *
 * 把数组按指定的个数分隔
 * @param array $array 要分割的数组
 * @param int $groupNum 分的组数
 */
function splitArray($array, $groupNum){
	if(empty($array)) return array();
	//数组的总长度
	$allLength = count($array);
	//个数
	$groupNum = intval($groupNum);
	//取余
	$yu = (int)($allLength%$groupNum);
	//取整
	$zheng = (int)(($allLength-$yu)/$groupNum);
	//结果集
	$result = array();
	//算出小数组可以有几个元素
	$s = array();
	if($yu > 0){
		for ($i=0; $i <$groupNum; $i++) {
			$s[$i] = $zheng;
			if($yu>=1){
				$s[$i] = $s[$i]+1;
			}
			$yu = $yu-1;
		}
	}else{
		return array_chunk($array, $zheng);
	}
	foreach ($s as $k => $v) {
		for ($i=0; $i < $v; $i++) {
			$result[$k][] = array_shift($array);
		}
	}
	return $result;
}

/**
 * 生成二维码
 * @param   $value      string      二维码内容
 * */
function createQr($value){
	vendor('phpqrcode.phpqrcode');

	$errorCorrectionLevel = 'L';//容错级别
	$matrixPointSize = 7;//生成图片大小

	//生成二维码图片
	$save_picture_path = QR_PATH . date("Y-m-d");
	if(!is_dir($save_picture_path)) mkdir($save_picture_path, 0777, true);

	$filename = $save_picture_path . '/' . time() . rand(1000,9999) . '.png';
	\QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
	$QR = $filename;        //已经生成的原始二维码图片文件
	$QR = imagecreatefromstring(file_get_contents($QR));
	imagepng($QR, 'qrcode.png');
	imagedestroy($QR);

	$filename_arr = explode('public', $filename);

	return $filename_arr[1];
}

function getRandStr($length){
	$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	$len = strlen($str)-1;
	$rand_str = '';
	for($i = 0; $i < $length; $i++){
		$num = mt_rand(0, $len);
		$rand_str .= $str[$num];
	}
	return $rand_str;
}

function createNo()
{
	$rule_info = Db::name('no_rule')->where(['id' => 1])->find();
	$rule_no = '';

	if($rule_info['no_header'] != '') $rule_no .= $rule_info['no_header'];
	if($rule_info['no_length'] > 0 && strlen($rule_info['no_header']) < $rule_info['no_length']) $rule_no .= getRandStr($rule_info['no_length'] - strlen($rule_info['no_header']));

	return $rule_no;
}